/**
 * Created with webstrom
 * author:金海宾
 * Date:2017/9/6
 * Time:17:32
 */
import Vue from 'vue';
import store from '../vuex/index';
import VueRouter from 'vue-router';
import layout from '../components/layout/index';
import test from '../components/test';
import {V_ROUTE} from '../../common/js/VueTypes';

// 将vuerouter挂载到vue上
Vue.use(VueRouter);

const router = new VueRouter({
    routes: [{
        name: 'menus',
        component: test,
        path: '/menus'
    }, {
        name: 'user',
        component: test,
        path: '/user'
    }, {
        name: 'nodelist',
        component: test,
        path: '/nodelist'
    }, {
        name: 'task',
        component: test,
        path: '/task'
    }, {
        name: 'version',
        component: test,
        path: '/version'
    }, {
        name: 'publish',
        component: test,
        path: '/publish'
    }]
});

/**
 * 计算面包屑导航
 * @param menus
 * @param lastMenu
 */
function getBreadcrumbArray(menus, lastMenu, dataArray) {
    let parent = menus.find(item => item.id === lastMenu.pid);
    if (parent) {
        dataArray.push(parent);
        getBreadcrumbArray(menus, parent, dataArray);
    }
}

// 路由跳转钱的钩子
router.beforeEach((to, from, next) => {
    /* 根据路径找到模块所对应的菜单对象
    根据菜单对象反推出当前菜单的祖宗菜单，用来渲染面包屑导航
    然后在把目标页对应的菜单添加到标签列表*/
    let fullPath = to.fullPath, origalMenu = store.getters.getOriginalMenu, sysMenus = store.getters.getMenus,
        toMenu = origalMenu.find(item => fullPath === item.path), breadcrumArray = [toMenu];

    // 获取面包屑导航数组
    getBreadcrumbArray(origalMenu, toMenu, breadcrumArray);
    breadcrumArray = breadcrumArray.reverse();

    // 设置面包屑导航
    store.SC(V_ROUTE, 'setBreadcrumb', breadcrumArray);
    store.SC(V_ROUTE, 'addRouter', toMenu);
    // 显示loadinbg窗口
    store.commit('setLoading', true);
    next();
});
// 离开前的钩子
router.afterEach((to, from) => {
    setTimeout(function () {
        store.commit('setLoading', false);
    }, 1000);
});

export default router;
